import React, { Component } from "react";
import axios from 'axios';
import PubSub from 'pubsub-js';

export default class HeroList extends Component {
    state = {
        heros: [],
    };
    render() {
        return (
            <div className="hero-list">
                {this.state.heros.map((item) => {
                    return (
                        <div key={item.id} className="item">
                            <img width="100%" src={item.avatar} alt="" />
                            <p>{item.name}</p>
                        </div>
                    );
                })}
            </div>
        );
    }

    async componentDidMount() {
        let res = await axios.get("https://api.xiaohigh.com/lol");
        //设置状态
        this.setState({
            heros: res.data
        });
        //设置订阅
        PubSub.subscribe('lolkeyword', async (name, data) => {
            //发送带关键字参数的请求
            let res = await axios.get('https://api.xiaohigh.com/lol', {params: {q: data}})
            //更新状态
            this.setState({
                heros: res.data
            })
        });
    }

    //将要卸载
    componentWillUnmount(){
        //取消订阅
        PubSub.unsubscribe('lolkeyword');
    }
}
